#include "Common.hpp"
#include "Log.hpp"

using namespace LogModule;

//  ./tcpclient server_ip server_port
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        std::cerr << "Usage: " << argv[0] << " server_ip server_port" << std::endl;
        exit(USAGE_ERROR);
    }

    Enable_Console_Log_Strategy();

    std::string server_ip = argv[1];
    uint16_t server_port = std::stoi(argv[2]);

    InetAddr server(server_ip, server_port);

    // 1. 创建套接字
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0)
    {
        LOG(LogLevel::FATAL) << "socket error!";
        exit(SOCKET_ERROR);
    }

    // 2. OS自动bind客户端的套接字

    // 3. 设置连接套接字
    int n = connect(sockfd, CONST_CONV(server.Addr()), server.AddrLen());
    if (n < 0)
    {
        LOG(LogLevel::FATAL) << "connect error!";
        exit(CONNECT_ERROR);
    }

    while(true)
    {
        std::cout << "please input @ ";
        std::string line;
        std::getline(std::cin,line);

        write(sockfd,line.c_str(),line.size());

        char buf[256];
        ssize_t s = read(sockfd,buf,sizeof(buf)-1);
        if(s > 0)
        {
            buf[s] = 0;
            std::cout << "server echo# " << buf << std::endl;
        }
    }

    close(sockfd);
    return 0;
}